using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Client;

namespace ShopForWeb.Api.Utils.Extensions
{
  public static class ControllerExtensions
  {
    public static int GetUserId(this ControllerBase controller)
    {
      var cookies = controller.HttpContext.Request.Cookies;
      string? valUserId;
      cookies.TryGetValue("userid", out valUserId);
      return Convert.ToInt32(valUserId ?? "");
    }

    public static string ImgSave(this ControllerBase controller, string base64Str, string src, string rootPath)
    {
      string defaultImg = @"/upload/orange.jpg";

      if (string.IsNullOrEmpty(base64Str) || base64Str.IndexOf("base64,") == -1)
      {
        if (src.Equals(defaultImg)) src = "";
        return src;
      }

      if (string.IsNullOrEmpty(src) || src.Equals(defaultImg))
        src = $"/upload/{Guid.NewGuid().ToString("N") + ".jpg"}";

      int index = base64Str.IndexOf(",") + 1;
      byte[] bytes = Convert.FromBase64String(base64Str.Substring(index));

      string filePath = rootPath + src.Replace("/", @"\");
      File.WriteAllBytes(filePath, bytes);
      return src;
    }
    public static void ImgDel(this ControllerBase controller, string src, string rootPath)
    {
      if (string.IsNullOrEmpty(src) || src.Equals("upload/orange.jpg"))
      {
        return;
      }
      string filePath = rootPath + src.Replace("/", @"\");
      if (File.Exists(filePath)) File.Delete(filePath);
    }
  }
}
